'use strict';
(function() {
	window.URL = window.URL || window.webkitURL;
	window.AudioContext = window.AudioContext || window.webkitAudioContext;

	document.documentElement.requestFullScreen = document.documentElement.requestFullScreen || document.documentElement.webkitRequestFullScreen;
	document.exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozExitFullscreen;

	navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
	window.CSSMatrix = window.CSSMatrix || window.WebKitCSSMatrix || window.MSCSSMatrix;

	if(! function() {}.bind) {
		Function.prototype.bind = function(context) {
			var self = this,
				args = Array.prototype.slice.call(arguments);

			return function() {
				return self.apply(context, args.slice(1));
			}
		};
	}

	if(!Date.now) {
		Date.now = function() {
			return new Date().getTime();
		};
	}
	/**       
	 * 对Date的扩展，将 Date 转化为指定格式的String       
	 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符       
	 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)       
	 * eg:       
	 * (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423       
	 * (new Date()).format("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04       
	 * (new Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04       
	 * (new Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04       
	 * (new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18       
	 */
	Date.prototype.format = function(fmt) {
		var o = {
			"M+": this.getMonth() + 1, //月份           
			"d+": this.getDate(), //日           
			"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
			"H+": this.getHours(), //小时           
			"m+": this.getMinutes(), //分           
			"s+": this.getSeconds(), //秒           
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度           
			"S": this.getMilliseconds() //毫秒           
		};
		var week = {
			"0": "日",
			"1": "一",
			"2": "二",
			"3": "三",
			"4": "四",
			"5": "五",
			"6": "六"
		};
		if(/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		if(/(E+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
		}
		for(var k in o) {
			if(new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	}

	if(window.Element) {
		Element.prototype.requestFullscreen = Element.prototype.requestFullscreen || Element.prototype.webkitRequestFullScreen || Element.prototype.mozRequestFullScreen;
		Element.prototype.on = Element.prototype.addEventListener;
		Element.prototype.off = Element.prototype.removeEventListener;
	}
	if(window.Audio) {
		Audio.prototype.autoPlay = function(callback) {
			var audio = this;
			audio.play();
			if(audio.paused) {
				var ev = function() {
					document.removeEventListener('touchstart', ev, true);
					audio.play();
					callback && callback();
				}
				if(/MicroMessenger/i.test(navigator.userAgent)) {
					if(window.WeixinJSBridge) {
						WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
							audio.play();
							callback && callback();
						});
					} else {
						document.addEventListener("WeixinJSBridgeReady", function() {
							WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
								audio.play();
								callback && callback();
							});
						}, false);
					}
				} else {
					document.addEventListener('touchstart', ev, true);
				}
			} else {
				callback && callback();
			}
		}
	}
	// requestAnimationFrame polyfill by Erik Möller.
	// Fixes from Paul Irish, Tino Zijdel, Andrew Mao, Klemen Slavič, Darius Bacon
	// MIT license
	;
	(function() {
		var vendors = ['webkit', 'moz'];
		for(var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
			var vp = vendors[i];
			window.requestAnimationFrame = window[vp + 'RequestAnimationFrame'];
			window.cancelAnimationFrame = (window[vp + 'CancelAnimationFrame'] || window[vp + 'CancelRequestAnimationFrame']);
		}
		if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
			||
			!window.requestAnimationFrame || !window.cancelAnimationFrame) {
			var lastTime = 0;
			window.requestAnimationFrame = function(callback) {
				var now = Date.now();
				var nextTime = Math.max(lastTime + 16, now);
				return setTimeout(function() {
						callback(lastTime = nextTime);
					},
					nextTime - now);
			};
			window.cancelAnimationFrame = clearTimeout;
		}
	}());
	// svg innerHTML outerHTML
	(function() {
		if(!Object.defineProperty || !window.SVGElement) {
			return;
		}
		if(!('outerHTML' in SVGElement.prototype)) {
			Object.defineProperty(SVGElement.prototype, 'outerHTML', {
				set: function(value) {
					var div = document.createElement('div'),
						df = document.createDocumentFragment(),
						parent = this.parentNode,
						childNodes;
					this.textContent = '';
					if(/<\/svg>$/.test(value.trim())) {
						div.innerHTML = value;
						childNodes = Array.prototype.slice.call(div.childNodes);
					} else {
						div.innerHTML = '<svg>' + value + '</svg>';
						childNodes = Array.prototype.slice.call(div.childNodes[0].childNodes);
					}
					for(var i = 0, l = childNodes.length; i < l; i++) {
						df.appendChild(childNodes[i]);
					}
					parent.insertBefore(df, this);
					parent.removeChild(this);
					div = null;
					df = null;
					parent = null;
					childNodes = null;
				},
				get: function() {
					return new XMLSerializer().serializeToString(this);
				}
			});
		}
		if(!('innerHTML' in SVGElement.prototype)) {
			Object.defineProperty(SVGElement.prototype, 'innerHTML', {
				set: function(value) {
					var div = document.createElement('div'),
						df = document.createDocumentFragment(),
						childNodes;
					div.innerHTML = '<svg>' + value + '</svg>';
					this.textContent = '';
					childNodes = Array.prototype.slice.call(this.childNodes);
					for(var i = 0, l = childNodes.length; i < l; i++) {
						this.removeChild(childNodes[i]);
					}
					childNodes = Array.prototype.slice.call(div.childNodes[0].childNodes);
					for(var i = 0, l = childNodes.length; i < l; i++) {
						df.appendChild(childNodes[i]);
					}
					this.appendChild(df);
					div = null;
					df = null;
					childNodes = null;
				},
				get: function() {
					var rep0 = new RegExp('^<' + this.nodeName + '.*?>', 'i'),
						rep1 = new RegExp('<\/' + this.nodeName + '>', 'i');
					return new XMLSerializer().serializeToString(this).replace(rep0, '').replace(rep1, '');
				}
			});
		}
	})();

	if(!window.localStorage) {
		alert('请关闭无痕模式');
	}
})();

var AKONG = window.AKONG || {};
AKONG.config = {
	DOMAIN: 'http://buer.bluej.cn/src/html/exports/',
	wxShare: false,
	dialogShow: false,
	isClick: false,
	debug: false,
	hasTouch: 'ontouchstart' in window,
	_autoplay: undefined
}
AKONG.ua = (function() {
	var ua = navigator.userAgent,
		obj = {
			name: ua,
			isAndroid: /android/i.test(ua),
			isIOS: /iphone os/i.test(ua),
			isIpad: /ipad/i.test(ua),
			isWM: /windows ce/i.test(ua) || /windows mobile/i.test(ua),
			isMidp: /midp/i.test(ua),
			isUc7: /rv:1.2.3.4/i.test(ua),
			isUc: /ucweb/i.test(ua) || /ucbrowser/i.test(ua),
			isWeiXin: /MicroMessenger/i.test(ua),
			isWebKit: /webkit/i.test(ua),
			isChrome: /Chrome/i.test(ua)
		}
	obj.isMobile = obj.isAndroid || obj.isIOS || obj.isIpad || obj.isWM || obj.isMidp || obj.isUc7 || obj.isUc;
	obj.isPC = !(typeof window.orientation === 'number');
	obj.isMac = /macintosh|mac os x/i.test(ua);
	if(ua.toLocaleLowerCase().indexOf('ucbrowser') > -1) {
		var control = navigator.control || {};
		if(control.gesture) {
			control.gesture(false);
		}
	}
	if(obj.isAndroid) {
		document.documentElement.classList.add('isAndroid');
	}
	if(obj.isIOS || obj.isIpad) {
		document.documentElement.classList.add('isIOS');
	}
	return obj;
})();
AKONG.query = {
	id: function(dom) {
		return document.getElementById(dom);
	},
	className: function(dom) {
		return document.getElementsByClassName(dom);
	},
	tag: function(dom) {
		return document.getElementsByTagName(dom);
	},
	one: function(dom) {
		return document.querySelector(dom);
	},
	all: function(dom) {
		return document.querySelectorAll(dom);
	},
	each: function(list, callback) {
		for(var i = 0, l = list.length || 0; i < l; i++) {
			callback(list[i], i);
		}
	},
	url: function(item) {
		var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
		return svalue ? svalue[1] : svalue;
	},
	urls: function() {
		var url = location.search;
		var theRequest = new Object(),
			strs;
		if(url.indexOf("?") != -1) {
			var str = url.substr(1);
			if(str.indexOf("&") != -1) {
				strs = str.split("&");
				for(var i = 0; i < strs.length; i++) {
					theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
				}
			} else {
				var key = str.substring(0, str.indexOf("="));
				var value = str.substr(str.indexOf("=") + 1);
				theRequest[key] = decodeURI(value);
			}
		}
		return theRequest;
	}
};
AKONG.req = {
	ajax: function(obj) {
		var method = obj.method ? obj.method.toLocaleLowerCase() : 'get',
			url = obj.url,
			data = obj.data,
			dataType = obj.dataType || 'json',
			async = obj.async === false ? false : true,
			cross = obj.cross || false,
			callback = obj.callback || false,
			error = obj.error || false,
			str = '',
			form = obj.form,
			xhr = new XMLHttpRequest(),
			fd;
		form && (fd = new FormData(form), method = 'post');
		if(data) {
			if(fd) {
				for(var i in data) {
					fd.append(i, data[i]);
				}
			} else {
				if(data instanceof Object) {
					for(var i in data) {
						str += (encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&');
					}
					str = str.substr(0, str.length - 1);
				} else {
					str += encodeURIComponent(data);
				}
			}
		}
		if(dataType == 'blob' || dataType == 'arraybuffer') {
			xhr.responseType = dataType;
		}
		if(obj.timeout) {
			xhr.timeout = obj.timeout;
			xhr.ontimeout = function(event) {
				error && error('请求超时！');
			}
		}
		if(method === 'get') {
			if(str) {
				if(url.indexOf('?') > -1) {
					url += '&' + str;
				} else {
					url += '?' + str;
				}
			}
		}
		if(cross) {
			xhr.withCredentials = true;
		}
		xhr.open(method, url, async);
		if(method === 'post' && !fd) {
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
		xhr.onload = function() {
			xhr.onload = null;
			switch(dataType) {
				case 'json':
					callback(JSON.parse(this.responseText));
					break;
				case 'blob':
				case 'arraybuffer':
					callback(this.response);
					break;
				default:
					callback(this.responseText);
					break;
			}
		}
		xhr.send(fd ? fd : (method === 'post' ? str : null));
	},
	jsonp: function(obj) {
		var script = document.createElement('script'),
			jsonp = obj.jsonp,
			url = obj.url,
			callbackName = obj.jsonpCallback || 'akong' + (Math.random() * 1000000000 >> 0).toString(16) + '_' + new Date().getTime(),
			rjsonp = /(=)\?(?=&|$)|\?\?/;
		window[callbackName] = obj.callback;

		if(/\?/.test(url)) {
			script.src = url + '&' + jsonp + '=' + callbackName;
		} else {
			script.src = url + '?' + jsonp + '=' + callbackName;
		}
		if(document.body) {
			document.body.appendChild(script);
		} else {
			document.head.appendChild(script);
		}
		script.onload = function() {
			window[callbackName] = null;
		}
	}
};
AKONG.require = function() {
	var length = arguments.length,
		self = this;
	if(length === 2) {
		var values = [];
		arguments[0].forEach(function(v) {
			if(self[v]) {
				values.push(self[v]);
			} else {
				values.push(undefined);
				if(AKONG.config.debug) {
					console.warn('has not ' + v);
				}
			}
		});
		arguments[1].apply(self, values);
	} else {
		arguments[0].apply(self);
	}
};
AKONG.others = (function() {
	var obj = {
		getOffset: function(el, el2) {
			var scene = el2 || document.body,
				l = el.offsetLeft,
				t = el.offsetTop;
			while(el = el.offsetParent) {
				if(el === scene) {
					break;
				}
				l += el.offsetLeft;
				t += el.offsetTop;
			}
			return {
				left: l,
				top: t
			};
		},
		getRandomColor: function() {
			var ran = ('000000' + ((Math.random() * (0xffffff + 1)) >> 0).toString(16)).substr(-6);
			return ['0x' + ran, '#' + ran];
		},
		getAllProperties: function(object, search, loop, bol) {
			var result = !!bol ? {
				funcProper: [],
				properties: []
			} : [];
			Object.getOwnPropertyNames(object).forEach(function(v, i) {
				if(v.toLowerCase().indexOf(search.toLowerCase()) > -1) {
					if(!bol) {
						result.push(v);
					} else {
						if(typeof object[v] === 'function') {
							result.funcProper.push(v);
						} else {
							result.properties.push(v);
						}
					}
				}
			});
			if(!!loop && object.__proto__) {
				result.protoProperties = obj.getAllProperties(object.__proto__, search, loop, bol);
			}
			return result;
		}
	};
	if(typeof document.hidden === 'boolean') {
		obj.hiddenEvents = [];
		obj.addHiddenEvent = function(fun) {
			if(obj.hiddenEvents.length === 0) {
				document.addEventListener("visibilitychange", function() {
					obj.hiddenEvents.forEach(function(v) {
						v(document.hidden, Date.now());
					});
				});
			}
			obj.hiddenEvents.push(fun);
		}
	}
	return obj;
})();

AKONG.require(['config', 'ua', 'query', 'req'], function(config, ua, $, req) {
	Object.defineProperty && Object.defineProperty(config, 'autoplay', {
		get: function() {
			if(typeof config._autoplay === 'boolean') {
				return config._autoplay;
			} else {
				var audio = new Audio();
				audio.play();
				config._autoplay = !audio.paused;
				audio = null;
				return config._autoplay;
			}
		}
	});
	if(config.debug || $.url('debug')) {
		document.addEventListener('contextmenu', function(e) {
			e.preventDefault();
		});
		document.write('<script src="js/debug.js" type="text/javascript" charset="utf-8"><\/script>');
	}
	if(ua.isWeiXin && config.wxShare) {
		document.write('<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript" charset="utf-8"><\/script><script src="js/WeixinApi.js" type="text/javascript" charset="utf-8"><\/script>');
	}
});